<template>
	<div>
		<div class="container">
			<el-tag
				v-for="tag in dynamicTags"
				:key="tag"
				closable
				size="small"
				:disable-transitions="false"
				@close="handleClose(tag)">
				{{ tag }}
			</el-tag>
			<el-row>
				<el-col :span="15">
					<div class='inputdiv'>
						<el-input ref="input" class='input-new-tag' v-model.trim='inputIndex' placeholder="请输入病床号并回车选中"
								  @keyup.enter='exactSearch()'>
							<template #suffix>
							
							</template>
							<template #append>
								<el-button @click="clearAlltag()" style="border-color: #97a8be; color: #fd5656">
									清空
								</el-button>
								<el-button @click="checkAlltag()" style="border-color: #97a8be; margin-left: 20px; color: #2d8cf0">
									全选
								</el-button>
							</template>
						</el-input>
					</div>
				</el-col>
				
				<el-col :offset="1" :span="2">
					<p style="text-align: center; margin-top: 5px; font-size: 15px">快捷语音：</p>
				</el-col>
				<el-col v-for="(hot, index) in hots" :span="2">
					<el-button v-if="hot !== null" size="small" style="padding: 0">
						<el-tag size="large"
								@click="submit(hot.url)"
								@close="removeHot(index)"
								closable>{{hot.title}}
						</el-tag>
					</el-button>
					<el-select v-model="hots[index]" v-if="hot === null"
							   size="small" placeholder="请选择"
							   style="width: 6em">
						<el-option v-for="item in voiceList"
								   :label="item.title"
								   :value="item">
							<span style="float: left; color: #606266">{{ item.title }}</span>
						</el-option>
					</el-select>
				</el-col>
				
			</el-row>
			
			<!-- 新增弹框 -->
			
			<el-divider content-position="center" style="margin-top: 1em">
				<div style="color: #20a0ff">请选择语音方式</div>
			</el-divider>
			<el-row style="margin-bottom: 3em">
				<el-col align="center">
					<el-tabs type="border-card" style="width: 50%">
						<el-tab-pane label="外接麦克风">
							<el-row>
								<el-col :offset="2" :span="16">
									<Recorder @blob="getFile"></Recorder>
								</el-col>
								<el-col :span="4">
									<el-button type="primary" size="small" @click="submit1">发布</el-button>
								</el-col>
							</el-row>
						</el-tab-pane>
						
						<el-tab-pane label="自定义语音库">
							<el-select placeholder="请选择语音" v-model="audio2" size="small">
								<el-option v-for="item in voiceList"
										   :label="item.title"
										   :value="item.url">
									<span style="float: left; color: #606266">{{ item.title }}</span>
									<span style="float: right; font-size: smaller; color: #999999">{{ item.comment }}</span>
								</el-option>
							</el-select>
							<el-button type="primary" style="margin-left: 2em" size="small" @click="submit2">发布</el-button>
						</el-tab-pane>
					</el-tabs>
				</el-col>
			</el-row>
			
			<el-row>
				<el-col :span='spanRoom(room)' v-for="(room, index) in searchData" :key="index">
					<el-card v-if="room != ''" body-style="padding: 8px" style="margin-bottom: 1em" >
						<el-row>
							<el-col :span="3">
								<el-tooltip content="全选 / 取消全选" effect="light" placement="top">
									<el-button size="medium" type="primary" style="padding: 0.5em"
											   @click="allBeds(index)" plain>
										{{room[0].room}}
									</el-button>
								</el-tooltip>
							</el-col>
							<el-col :span="21">
								<el-checkbox-group v-model="idList[index]" fill="#87CEFA">
									<el-checkbox-button v-for="bed in room" :label="bed.queNumber">
										{{bed.queNumber}} {{name_format(bed.name)}}
									</el-checkbox-button>
								</el-checkbox-group>
							</el-col>
						</el-row>
					</el-card>
				</el-col>
			</el-row>
		</div>
	</div>
</template>


<script>
import {getPatientList, getVoiceList, shoutSubmit, upload} from "../api/broadcast";
import {watch,reactive,ref, computed} from "vue";
import {ElMessage} from "element-plus";
import Recorder from "../components/Recorder.vue";
import router from "../router";


export default {
	components: {Recorder},
	setup() {
		let patientList = ref([]);
		//选中的病人id
		let idList = ref([]);
		//初始化语音库列表
		let voiceList = ref([]);
		//快捷语音
		const hots = ref(JSON.parse(localStorage.getItem('hot_voices')) || [null, null, null]);
		//录音文件
		const file = ref(null);
		//选中的音频地址
		const audio2 = ref('');
		//获取病人列表
		getPatientList()
			.then((res) => {
				if (res.code > 0) {
					ElMessage.error('请求失败，请稍后重试！');
				} else {
					patientList.value = res.data.patientList;
					searchData.value = res.data.patientList;
					//初始化房间选择列表
					for (let i = 0; i < patientList.value.length; i++) {
						idList.value[i] = [];
					}
				}
			})
			.catch(() => {
				ElMessage.error('服务器未启动或其它错误！');
			});
		
		const name_format = (name)=>{
			if (name === null) return
			if(name.length > 4){
				return name.slice(0,4)+'...'
			}
			return name
		}
		
		//快捷键相关：
		let inputIndex = ref('')
		let searchData = ref([])
		//删除tag
		const handleClose = ((tag)=>{
			//dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
			idList.value.forEach((item)=>{
				var index = item.indexOf(tag + "")
				if(index != -1){
					item.splice(index, 1)
					return
				}
			})
		})
		const handleInputConfirm =(()=>{
			if(dynamicTags.value.findIndex(tag=>tag  === parseInt(inputIndex.value)) === -1){
				dynamicTags.value.push(parseInt(inputIndex.value))
			}
		})
		let dynamicTags = computed(()=>{
			let temp = []
			idList.value.forEach((item)=>{
				item.forEach((bed)=>{
					temp.push(bed)
				})
			})
			return temp
		})
		
		const spanRoom = (room)=>{
			if(room === ''){
				return 0;
			}else{
				return 6;
			}
		}
		const exactSearch = ()=>{	
			if(inputIndex.value === ''){
				return 
			}
			var flag = 0
			patientList.value.forEach((item,index)=>{
                item.forEach((bed)=>{
					//已经选中的不必再次选中
					if(bed.id === parseInt(inputIndex.value)){
						flag = 1
						if(idList.value[index].findIndex(id => id === bed.id) < 0){
							idList.value[index].push(bed.id)
						}
					}
                })
			})
			if(flag){
				handleInputConfirm()
			}else{
				ElMessage.error('没有该病床！')
			}
			inputIndex.value=''
		}
		const clearAlltag = ()=>{
			dynamicTags.value = []
			for (let i = 0; i < patientList.value.length; i++) {
				idList.value[i] = [];
			}
		}
		//全选所有病床
		const checkAlltag = ()=>{
			var flag = true
			//当前为全选状态则取消全选，否则全选
			idList.value.forEach((room)=>{
				let index = idList.value.indexOf(room)
				if(room.length !== patientList.value[index].length){
					flag = false
				}
			})
			if(flag){
				idList.value.forEach((room)=>{
					let index_ = idList.value.indexOf(room)
				    idList.value[index_]=[]
				})
			}else{
				idList.value.forEach((room)=>{
					let index_1 = idList.value.indexOf(room)
				    //已经选中的不需要再次选中
					patientList.value[index_1].forEach((item)=>{
						if (idList.value[index_1].findIndex(id => id === item.queNumber) < 0) {
						idList.value[index_1].push(item.queNumber);
					}
					})
				})
			}
		}
		watch(inputIndex,(value)=>{
			inputIndex.value = value.replace(/\D/g, '');
			if(inputIndex.value>1000){
				inputIndex.value=''
				ElMessage.error('只能输入0-1000的数字!')
			}else if(inputIndex.value === '0'){
				inputIndex.value=''
				ElMessage.error('只能输入0-1000的数字!')
			}
		})
		
		//浏览器本地存储
		watch(hots,(value)=>{
			localStorage.setItem('hot_voices',JSON.stringify(value))
		},{deep:true});
		
		//移除快捷语音
		const removeHot = (index) => {
		  	hots.value[index] = null;
		}
		
		//定义全选/取消全选按钮
		const allBeds = (index) => {
			//当前为全选状态则取消全选，否则全选
			if (idList.value[index].length === patientList.value[index].length) {
				idList.value[index] = [];
			} else {
				patientList.value[index].forEach( function (item) {
					//已经选中的不需要再次选中
					if (idList.value[index].findIndex(id => id === item.queNumber) < 0) {
						idList.value[index].push(item.queNumber);
					}
				})
			}
		}
		//获取录音器组件传来的url
		const getFile = (f) => {
			file.value = f;
		}
		
		//定义获取语音库列表操作
		const getVoiceShowList = () => {
			getVoiceList()
				.then((res) => {
					voiceList.value = res.data;
				})
				.catch(() => {
					ElMessage.error('服务器未启动或其它错误！');
				})
		};
		getVoiceShowList();
		
		//定义提交操作
		const submit = (url) => {
		  	const params = reactive({
				url: url,
				beds: idList.value.flat(2)
			});
			if (params.beds.length === 0 || params.url === '') {
				ElMessage.error('请在选中对象后进行喊话！');
				return;
			}
			//提交喊话请求
			shoutSubmit(params)
				.then((res) => {
					if (res.data === true) {
						ElMessage.success('发送成功！');
					} else {
						ElMessage.error('发送失败，请稍后重试！');
					}
				})
				.catch(() => {
					ElMessage.error('服务器未启动或其它错误！');
				});
		}
		
		
		const submit1 = () => {
			if (idList.value.flat(2).length === 0) {
				ElMessage.error('请在选中对象后进行喊话！');
				return;
			}
			//将文件上传至服务器
			upload(file.value)
				.then((res) => {
					if (res.code === 0) {
						submit(res.data);
					} else {
						ElMessage.error('服务器上传失败，请稍后重试！');
					}
				})
				.catch(() => {
					ElMessage.error('服务器未启动或其它错误！');
				})
		}
		
		const submit2 = () => {
		  	submit(audio2.value);
		}
		return {
			idList,
			patientList,
			audio2,
			voiceList,
			inputIndex,
			searchData,
			dynamicTags,
			hots,
			spanRoom,
			allBeds,
			getFile,
			submit,
			submit1,
			submit2,
			handleClose,
			handleInputConfirm,
			exactSearch,
			clearAlltag,
			checkAlltag,
			removeHot,	
			name_format,
		}
	},
	mounted() {
		this.$refs.input.focus();
	}
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 5px;
}
.inputdiv{
  width:100%;
  margin-bottom:10px;
  margin-top:2px	
}
.input-new-tag {
  width:40%; 
}
</style>
